package com.feeling.oafeeling.common;


import com.feeling.oafeeling.common.pojo.AjaxResult;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理
 */
//用于标识当前类为REST风格对应的异常处理器
@ControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody
public class GlobalExceptionHandler {
    /**
     * 异常处理方法
     * @param ex
     * @return
     */
    //@ExceptionHandler用于设置当前处理器类对应的异常类型
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public AjaxResult exception(SQLIntegrityConstraintViolationException ex){
        if (ex.getMessage().contains("Duplicate entry")){
            String[] sp = ex.getMessage().split(" ");
            String msg = sp[2] + "已存在";
            return AjaxResult.error(msg);
        } else if (ex.getMessage().contains("Cannot delete or update a parent row")) {
            return AjaxResult.error("当前分类有关联菜品，不能删除");
        }
        return AjaxResult.error("未知错误");
    }

    @ExceptionHandler(MyCustomException.class)
    public AjaxResult doBusinessException(MyCustomException ex){
        System.out.println(ex.getMessage());
        return AjaxResult.error("违规操作");
    }
}
